import $global from '@/common/js/global.js'
import XDate from '@/common/js/xdate.min.js'      //日期插件
import $md5 from '@/common/js/md5.js'

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
module.exports = {
	$global: $global,
	prefix: $global.prefix,
	host: $global.host,
	pagingArray:new Object,
	getShareInfo(title,imageUrl,path,noSave){
		var shareInfo;
		if(title!=undefined){
			shareInfo = {
				title:title,
				imageUrl:imageUrl,
				path:path
			};
			if(noSave==undefined) this.setStorage("ShareInfo",shareInfo);
		}else{
			shareInfo= this.getStorage("ShareInfo");
			if(shareInfo==undefined){
				shareInfo = {
					title:"",
					imageUrl:"",
					path:""
				};
			}
		}
		var userInfo = this.getStorage("UserInfo");
		if(this.isEmpty(shareInfo.path)){
			shareInfo.path = "/pages/index/index?spreadcode=" + (userInfo ? userInfo.SpreadCode : "");
		}
		if(this.isEmpty(shareInfo.title)){
			shareInfo.title = $global.appName;
		}
		if(this.isEmpty(shareInfo.imageUrl)){
			shareInfo.imageUrl = "../../static/share.png";
		}
		return shareInfo;
	},
	isClick(){
		var isClick = this.getStorage("IsClick");
		if(isClick==1)
		{
			return true;
		}else{
			this.setStorage("IsClick",1);
			var th = this;
			var curSetTimeout = setTimeout(function(){
				th.removeStorage("IsClick");
			},1000);
			
			if(curSetTimeout) clearTimeout(curSetTimeout);
			return false;
		}
	},
	getUrl(index){
		var url = getCurrentPages()[index].route;
		var options = getCurrentPages()[index].options;
		if(options){
			url = url + "?"
			for (var key in options) {
				url = url + key + "=" + options[key] + "&";
			}
		}
		return "../../" +　url;
	},
	iosPage(){
		//当输入框失焦，软键盘收起后，页面未恢复
		// #ifdef H5
		uni.getSystemInfo({
			success: function (res) {
				if(res.platform=='ios'){
					// $("input,select").blur(function () {
					// 	setTimeout(function () {
					// 		var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
					// 		window.scrollTo(0, Math.max(scrollHeight - 1, 0));
					// 	}, 100)
					// });
				}
			}
		});
		// #endif
	},
	hideBack(show){
		if(!show){
			if(getCurrentPages().length==1){
				// #ifdef H5
				document.getElementsByClassName("uni-page-head-hd")[0].style.display = "none";
				// #endif
			}
		}
	},
	toMap:function(endPoint){
		let plugin = requirePlugin('routePlan');
		//https://lbs.qq.com/dev/console/key/add 配置授权公众号
		let key = '6LWBZ-T3S34-4BZUD-XM4PX-VGVVO-QUBB3';  //使用在腾讯位置服务申请的key
		let referer = '珠海景山道';   //调用插件的app的名称
		wx.navigateTo({
		    url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + JSON.stringify(endPoint)
		});
	},
	scrollTo:function(id,minus){
		if(minus==undefined) minus = 0;
		var scrollTop = 0;
		var offsetTop = 0;
		// #ifdef H5
		offsetTop = 44
		// #endif
		
		uni.createSelectorQuery().select("#" + id).boundingClientRect(function(rects){
			console.log(rects)
			var query = uni.createSelectorQuery()
			query.select('#main').boundingClientRect()
			query.selectViewport().scrollOffset()
			query.exec(function(res){
				uni.pageScrollTo({
					scrollTop: rects.top + res[1].scrollTop - offsetTop - minus,
					duration: 300
				})
			})
		}).exec();
	},
	toast:function(title){
		uni.showToast({title:title,icon:"none",duration:2500});
	},
	alert:function(content,confirmSuccess,title,confirmText){
		if(content==null) content = "";
		content = this.replaceAll(content,'<br />','\n');
		uni.showModal({
			title: (title==undefined ? "温馨提示" : title),
			content:content,
			showCancel: false,
			confirmText: (confirmText==undefined ? "确定":confirmText),
			confirmColor: $global.colorTheme,
			success(res) {
				if (res.confirm) {
					if(confirmSuccess) confirmSuccess();
				}
			}
		});
	},
	kf:function(content,tel){
		content = this.replaceAll(content,'<br />','\n');
		uni.showModal({
			title: "温馨提示",
			content:content + tel,
			showCancel: true,
			confirmText: "拨打",
			success(res) {
				if(res.confirm){
					uni.makePhoneCall({
						phoneNumber: tel
					});
				}
			}
		});
	},
	confirm:function(content,success,title){
		uni.showModal({
			title: (title==undefined ? "温馨提示" : title),
			content:content,
			confirmText: "确定",
			confirmColor: $global.colorTheme,
			success(res) {
				if (res.confirm) {
					if(success) success();
				}
			}
		});
	},
	webView:function(title,url){
		var pageName = "web-view";
		if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
			pageName = "web-view-ios";
		}
		this.setStorage("WebUrl",url);
		this.to("../" + pageName + "?title=" + (title ? title : ""));
	},
	to:function(url,animation){
		uni.navigateTo({ 
			url: url , 
			animationType: (animation ? animation : 'pop-in'),
		    animationDuration: 300,
		});
	},
	href:function(url){
		uni.redirectTo({ url: url });
	},
	back:function(delta){
		if(getCurrentPages().length==1){
			this.href("../index/index");
		}else{
			uni.navigateBack({
				delta: (delta ? delta : 1),
				animationType: 'pop-out',
			    animationDuration: 300,
			});
		}
	},
	backIndex:function(){
		uni.navigateBack({
			delta: getCurrentPages().length + 1
		});
	},
	setStorage:function(key,value){
		key= $global.prefix + key;
		uni.setStorage({
			key: key,
			data: value,
			success: function () {
				return true;
			},fail:function(data){
				console.log('error:' + JSON.stringify(data));
				return false;
			}
		});
	},
	getStorage:function(key){
		var obj = uni.getStorageSync($global.prefix + key);
		if(obj=="") obj = undefined;
		return obj;
	},
	removeStorage:function(key){
		return uni.removeStorageSync($global.prefix + key);
	},
	removeStorageList:function(keys){
		var arr = keys.split(',');
		arr.forEach(function(item,index){
			uni.removeStorageSync($global.prefix + item);
		});
		return true;
	},
	isEmpty:function(vl){
		if (vl == "" || vl == null || vl == undefined) {
            return true;
        } else {
            return false;
        }
	},
	noEmpty:function(vl){
		return !this.isEmpty(vl);
	},
	replaceAll:function (sourceText, oldText, newText) {
		if(sourceText!=undefined){
			var reg=new RegExp(oldText,"g"); //创建正则RegExp对象
			return sourceText.toString().replace(reg,newText);
		}else{
			return "";
		}
        // var raRegExp = new RegExp(oldText.replace(/([\(\)\[\]\{\}\^\$j\+\-\*\?\.\"\'\|\/\\])/g, "\\$j1"), "ig");
        // return sourceText.replace(raRegExp, newText);
    },
	fmtImg:function(value,tableName,sizeStr){
	    if (this.isEmpty(value)) {
			return "../Resources/noimg.jpg";
		} else {
			if (value.lastIndexOf("http") == -1) {
				return "http://yyimgs.b0.upaiyun.com/images/" + tableName + "/" + value + (sizeStr == undefined ? "" : "!" + sizeStr);
			} else {
				return value;
			}
		}	
	},
	getWeek:function (dateString) {
        var date;
		if(this.isEmpty(dateString)){
			date = new Date();
		}else{
			var dateArray = dateString.split("-");
			date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
		}
		if(date.Format("yyyy-MM-dd")==new Date().Format("yyyy-MM-dd"))
		{
			return "今天";
		}else{
			return "周" + "日一二三四五六".charAt(date.getDay());
		}
    },
	getDay:function (diffDate) {
		var day = parseInt(new XDate(new XDate().toString("yyyy-MM-dd")).diffDays(new XDate(diffDate)));
		switch (day) {
			case 0:
				day = "今天";
				break;
			case 1:
				day = "明天";
				break;
			case 2:
				day = "后天";
				break;
			default:
				day = day + "天后";
				break;
		}
		return day;
	},
	getWindow:function(){
		return uni.getSystemInfoSync();
	},
	checkForm:function(formData){
		if(formData)
		{
			var len = formData.length;
			for (var i=0;i<len;i++) {
				var item = formData[i];
				if(item.Value==undefined) item.Value = "";
				var checkValue = this.replaceAll(item.Value," ","");
				if(checkValue=="" && !item.noCheck)
				{
					if(item.Desc){
						uni.showToast({title:item.Desc,icon:"none"});
					}else{
						uni.showToast({title:"请输入" + item.Name,icon:"none"});
					}
					return false;
				}else{
					if(checkValue!=""){
						///^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
						///^1\d{10}$/
						if (item.IsMobile && !new RegExp(/^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/).test(checkValue)) {
							uni.showToast({title:item.Name + "格式不正确",icon:"none"});
							return;
						}else if (item.IsIDCard && !this.checkIDCard(checkValue)) {
							uni.showToast({title:item.Name + "格式不正确",icon:"none"});
							return;
						}else if (item.IsBirthday && new XDate(checkValue) > new XDate()) {
							uni.showToast({title:item.Name + "不能大于当前日期",icon:"none"});
							return;
						}else if(item.isCE){
							var regu = "^[a-zA-Z\u4e00-\u9fa5]+$";
							var re = new RegExp(regu);
							if (!re.test(checkValue)) {
								uni.showToast({title:item.Name + "只支持汉字或字母",icon:"none"});
								return;
							}
						}
					}
				}
			}
		}
		return true;
	},
	checkForms:function(formData){
		if(formData)
		{
			var len = formData.length;
			for (var i=0;i<len;i++) {
				var item = formData[i];
				if(item.value==undefined) item.value = "";
				var checkValue = this.replaceAll(item.value," ","");
				if(checkValue=="" && !item.noCheck && !item.noShow && item.editType!='v')
				{
					if(item.desc){
						uni.showToast({title:item.desc,icon:"none"});
					}else{
						uni.showToast({title:"请输入" + item.text,icon:"none"});
					}
					return false;
				}else{
					if(checkValue!=""){
						if (item.isMobile && !new RegExp(/^1\d{10}$/).test(checkValue)) {
							uni.showToast({title:item.text + "格式不正确",icon:"none"});
							return false;
						}if (item.isEmail && !new RegExp(/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/).test(checkValue)) {
							uni.showToast({title:item.text + "格式不正确",icon:"none"});
							return false;
						}else if (item.isIDCard && !this.checkIDCard(checkValue)) {
							uni.showToast({title:item.text + "格式不正确",icon:"none"});
							return false;
						}else if (item.isBirthday && new XDate(checkValue) > new XDate()) {
							uni.showToast({title:item.text + "不能大于当前日期",icon:"none"});
							return false;
						}else if(item.isCE){
							var regu = "^[a-zA-Z\u4e00-\u9fa5]+$";
							var re = new RegExp(regu);
							if (!re.test(checkValue)) {
								uni.showToast({title:item.text + "只支持汉字或字母",icon:"none"});
								return false;
							}
						}else if(item.type=="address" && item.Province==""){
							uni.showToast({title:"请选择城市",icon:"none"});
							return false;
						}
						
						//关联列验证
						if(item.rIndex){
							var rItem = formData[item.rIndex];
							if(this.replaceAll(rItem.value," ","")!=checkValue){
								uni.showToast({title:rItem.text + "必须与" + item.text + "一致",icon:"none"});
								return false;
							}
						}
					}
				}
			}
			var formInfo = "";
			formData.forEach(function(item,index){
				if(item.editType!='v'){
					var vl = item.value ? item.value.toString().replace(/[\r\n]/g, "<br>") : "";
					if(item.type=="password" && vl.length<32){
						vl = $md5.hex_md5(vl);
					}else if(item.type=="img" && vl!=""){
						vl = vl.substring(vl.lastIndexOf("/") + 1,vl.lastIndexOf("!"));
					}
					formInfo = formInfo + (formInfo=="" ? "" : ",") + '"' + item.name + '":"' + vl + '"';
					if(item.type=="address"){
						formInfo = formInfo + "," + '"Area":"' + item.area + '"';
					}
				}
			});
			return JSON.parse("{" + formInfo + "}");
		}else{
			return false;
		}
	},
	getStaticUrl(name){
		// #ifdef H5
		return "../../static/" + name;
		// #endif
		
		// #ifndef H5
		return "static/" + name;
		// #endif
	},
	checkIDCard:function (code) {
        code = this.replaceAll(code," ",""); //code.replace(eval("/" + " " + "/gi"), "");
        //身份证号合法性验证 
        //支持15位和18位身份证号
        //支持地址编码、出生日期、校验位验证
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
        var tip = "";
        var pass = true;
        code = code.toUpperCase();
        //if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {

        if (code.length != 18) {
            tip = "身份证号格式错误";
            pass = false;
        } else if (!city[code.substr(0, 2)]) {
            tip = "地址编码错误";
            pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    tip = "校验位错误";
                    pass = false;
                }
            } else {
                tip = "输入二代身份证";
                pass = false;
            }
        }
        return pass;
    },
	getRequest:function(name) {
		var url = location.search; //获取url携带的参数
		var urlParams = new Object();
		if (url.indexOf("?") != -1) {
		    var str = url.substr(1);
		    var strs = str.split("&");
		    for(var i = 0; i < strs.length; i ++) {
		        urlParams[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
		    }
		}
		return urlParams[name];
	},
	getFormIDs:function(e){
		var formIds = this.getStorage("FormIDs");
		if(formIds==undefined) formIds = "";
		
		// #ifdef MP-TOUTIAO
		var formId = "";
		if(typeof e === "string"){
			formId = e;
		}else{
			if (e && e.detail.formId != 'the formId is a mock one') {
				formId = e.detail.formId;
		    }
		}
		if (formId!="") {
			if(formIds=="") 
			{
				formIds = formId;
			}else{
				if(formIds.length<500){
					formIds = formIds + "," + formId;
				}
			}
			this.setStorage("FormIDs",formIds);
		}
		// #endif
		return formIds;
	},
	initPage:function(pageOptions){
		var th = this;
		switch (pageOptions.pageType) {
            case undefined:
            case "list"://列表数据加载
				//设置分页模式值
				if(pageOptions.id==undefined)
				{
					pageOptions.id = "pageId";
				}
				var paging;
				if(!pageOptions.ajaxOptions.first) paging = th.pagingArray[pageOptions.id];
				
				switch (pageOptions.ajaxOptions.pageMode) {
					case "time": //时间类型分页
						pageOptions.ajaxOptions.data.LastSign = (paging ? paging : "");
					    if(!paging) th.pagingArray[pageOptions.id] = pageOptions.ajaxOptions.data.lastSign;
						break;
					case "page": //页码类型分页
					default:
						pageOptions.ajaxOptions.data.pageNum = (paging ? paging : 1);
						pageOptions.ajaxOptions.data.pageSize = (paging ? paging : 10);
						if(!paging) th.pagingArray[pageOptions.id] = pageOptions.ajaxOptions.data.pageNum;
						break;
				}
				
                pageOptions.ajaxOptions.success = function (data) {
                    switch (data.flag.toString()) {
						case "0"://返回数据
						case "200"://返回数据
                        case "1000"://返回数据
                            if (pageOptions.success) pageOptions.success(data.rows ? data.rows : data.data,data);
                            //相关相关分页参数
                            var pageData = "";
                            switch (pageOptions.ajaxOptions.pageMode) {
                                case "time": //时间类型分页
									th.pagingArray[pageOptions.id] = data.lastSign;
									break;
								case "page": //页码类型分页
							    default:
								    // th.pagingArray[pageOptions.id] = th.pagingArray[pageOptions.id]+ 1;
									pageOptions.ajaxOptions.data.pageNum = pageOptions.ajaxOptions.data.pageNum + 1
									break;
                            }
                            break;
                        case "-1"://无数据
						    if (pageOptions.success) pageOptions.success(undefined,data);
                            break;
                        default:
						    console.log('error:' + JSON.stringify(data));
                            break;
                    }
                }
                //第一次加载数据
                th.initAjax(pageOptions.ajaxOptions);
			    break;
		    case "detail":
			    pageOptions.ajaxOptions.success = function (data) {
			        switch (parseInt(data.flag)) {
			            case 1000://返回数据
			                if (pageOptions.success) pageOptions.success(data.data);
			                break;
			            case -1://无数据
			    		    if (pageOptions.success) pageOptions.success(undefined);
							th.alert("访问的数据不存在或已删除");
			                break;
			            default:
			    		    console.log('error:' + JSON.stringify(data));
							th.alert(data.message);
			                break;
			        }
			    }
			    //第一次加载数据
			    th.initAjax(pageOptions.ajaxOptions);
				break;
		}
	},
	initAjax:function (ajaxOptions) {
		//ajaxOptions.loading = false;
		if(ajaxOptions.loadText) ajaxOptions.loading = true;
		if (ajaxOptions.loading)
		{
			var title = (ajaxOptions.loadText ? ajaxOptions.loadText : "正在加载...");
		    uni.showLoading({title:title});
		}

		if(ajaxOptions.url.lastIndexOf($global.host)==-1 && ajaxOptions.url.substring(0,4)!="http")
		{
			ajaxOptions.url = $global.host + ajaxOptions.url;
		}
		//补填AppID
		var userInfo = this.getStorage("UserInfo");
		
		if(ajaxOptions.data==undefined){
			ajaxOptions.data = {};
		}
		
		if(ajaxOptions.data && ajaxOptions.data.AppID==undefined && userInfo && userInfo.AppID!=undefined){
			ajaxOptions.data.AppID = userInfo.AppID;
		} 
		
		for(var key in ajaxOptions.data){
			if(ajaxOptions.data[key]==undefined){
				ajaxOptions.data[key] = "";
			}
		}  
		
		// #ifdef MP-TOUTIAO
		var formIds = this.getFormIDs();
		if(formIds!=""){
			ajaxOptions.data.FormIDs = formIds;
			this.removeStorage("FormIDs");
		} 
		// #endif

		//自定义请求头信息
		var headers;
		// #ifndef H5
		// #endif
		var time = new XDate().toString("yyyy-MM-dd HH:mm:ss");
		headers = {
			'APITime': time,
			'APIToken': $md5.hex_md5('&' + time + '&'),
			"Content-Type": (ajaxOptions.contentType==undefined ? "application/json":"application/x-www-form-urlencoded")  
			//"Content-Type": (ajaxOptions.type=="post" ? "application/x-www-form-urlencoded" : "application/json")  
		}
		
		if (ajaxOptions.data){
			ajaxOptions.data.qv = Date.parse(new Date());
		}else{
			ajaxOptions.data = {qv: Date.parse(new Date())};
		}

		uni.request({
			url: ajaxOptions.url,
			method:(ajaxOptions.type ? ajaxOptions.type : "get"),
			dataType: (ajaxOptions.dataType ? ajaxOptions.dataType : 'json'),
			timeout: (ajaxOptions.timeout ? ajaxOptions.timeout : 30000),
			header: headers,
			data: ajaxOptions.data,
			success: (res) => {
				if (res.statusCode == 200) {
					res.data.flag = res.data.code;
					if(res.data.flag==200) res.data.flag = 0;
					if(res.data.data==null){
						res.data.data = [];
					}
					if(ajaxOptions.success) ajaxOptions.success(res.data);
				}else{
					this.alert("网络故障，请稍后重试。");
					console.log('error:' + JSON.stringify(res));
				}
			    if (ajaxOptions.loading) uni.hideLoading();
			},
			fail: (data, code) => {
				
				if (ajaxOptions.loading) uni.hideLoading();
				if(ajaxOptions.error){
					ajaxOptions.error();
				}else{
					this.alert("网络故障，请稍后重试。");
				} 
				console.log('error:' + code + ",data:" + JSON.stringify(data));
			}
		});
    }
}
